package com.hbnu.jdbc;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 需求：银行转账案例
 *
 * @author kittychen
 * @since 2025-10-22 14:42
 */
public class JdbcDemo06 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            InputStream resourceAsStream = JdbcDemo05.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            properties.load(resourceAsStream);

            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String user = properties.getProperty("username");
            String password = properties.getProperty("password");
            Class.forName(driver);

            connection = DriverManager.getConnection(url, user, password);

            // 开启事务
            connection.setAutoCommit(false);

            String sql1 = "update tb_user set salary = salary - ? where id = ?";
            String sql2 = "update tb_user set salary = salary + ? where id = ?";

            // id为2的人转1000出去
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setDouble(1, 1000);
            preparedStatement.setInt(2, 2);
            int count = preparedStatement.executeUpdate();

            int i = 10 / 0;

            // id为4的人收款1000
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setDouble(1, 1000);
            preparedStatement.setInt(2, 4);
            count += preparedStatement.executeUpdate();

            // 提交事务
            connection.commit();

            System.out.println(count == 2 ? "转账成功" : "转账失败");
        } catch (Exception e) {
            try {
                // 回滚事务
                if (connection != null) {
                    connection.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
